<template>
  <div class="orders-view">
    <div class="page-header">
      <h1>订单管理</h1>
      <p>管理用户订单信息、状态和支付记录</p>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="filter-card" shadow="hover">
      <el-form :model="searchForm" inline>
        <el-form-item label="订单号/用户">
          <el-input
            v-model="searchForm.search"
            placeholder="请输入订单号或用户昵称"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>

        <el-form-item label="订单状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="待支付" value="pending_payment" />
            <el-option label="待发货" value="processing" />
            <el-option label="待收货" value="shipped" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="已退款" value="refunded" />
          </el-select>
        </el-form-item>

        <el-form-item label="下单时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="handleReset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="content-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>订单列表 ({{ pagination.total }})</span>
          <div class="header-actions">
            <el-button :icon="Download" @click="handleExport">
              导出订单
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="orderList"
        style="width: 100%"
      >
        <el-table-column prop="order_number" label="订单号" width="180" />

        <el-table-column label="用户信息" width="150">
          <template #default="{ row }">
            <div class="user-info">
              <div class="user-name">{{ row.user_nickname || '未知用户' }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="total_amount" label="订单金额" width="120" align="center">
          <template #default="{ row }">
            <div class="amount-info">
              <div class="total-amount">¥{{ row.total_amount?.toFixed(2) || '0.00' }}</div>
              <div class="payment-amount">实付: ¥{{ row.payment_amount?.toFixed(2) || '0.00' }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="订单状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="下单时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column prop="payment_time" label="支付时间" width="180" align="center">
          <template #default="{ row }">
            {{ row.payment_time ? formatDate(row.payment_time) : '-' }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              :icon="View"
              @click="handleViewDetail(row)"
            >
              查看详情
            </el-button>
            <el-dropdown
              v-if="row.status === 'processing'"
              @command="(command) => handleStatusChange(row, command)"
            >
              <el-button type="warning" size="small">
                更多操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="shipped">标记发货</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, View, Download, ArrowDown } from '@element-plus/icons-vue'
import { request } from '@/utils/request'

// 路由
const router = useRouter()

// 响应式数据
const loading = ref(false)
const orderList = ref([])
const dateRange = ref([])

// 搜索表单
const searchForm = reactive({
  search: '',
  status: '',
  start_date: '',
  end_date: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 计算属性 - 处理日期范围
const searchParams = computed(() => {
  const params = { ...searchForm }
  if (dateRange.value && dateRange.value.length === 2) {
    params.start_date = dateRange.value[0]
    params.end_date = dateRange.value[1]
  }
  return params
})

// 获取订单列表
const fetchOrderList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchParams.value
    }

    const response = await request.get('/orders', { params })
    orderList.value = response.data || []
    pagination.total = response.pagination?.total || 0
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchOrderList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    search: '',
    status: '',
    start_date: '',
    end_date: ''
  })
  dateRange.value = []
  pagination.page = 1
  fetchOrderList()
}

// 查看订单详情
const handleViewDetail = (order: any) => {
  router.push(`/orders/${order.id}`)
}

// 状态变更
const handleStatusChange = async (order: any, command: string) => {
  try {
    await ElMessageBox.confirm(
      `确定要将订单 ${order.order_number} 标记为已发货吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await request.put(`/orders/${order.id}/status`, { status: command })
    ElMessage.success('订单状态更新成功')
    fetchOrderList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新订单状态失败:', error)
      ElMessage.error('更新订单状态失败')
    }
  }
}

// 导出订单
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  fetchOrderList()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchOrderList()
}

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'pending_payment': 'warning',
    'processing': 'primary',
    'shipped': 'info',
    'completed': 'success',
    'cancelled': 'danger',
    'refunded': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'pending_payment': '待支付',
    'processing': '待发货',
    'shipped': '待收货',
    'completed': '已完成',
    'cancelled': '已取消',
    'refunded': '已退款'
  }
  return statusMap[status] || '未知状态'
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchOrderList()
})
</script>

<style scoped>
.orders-view {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
}

.content-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.user-info {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-weight: 500;
  color: #303133;
}

.amount-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.total-amount {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.payment-amount {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.el-table {
  font-size: 14px;
}

.el-table .cell {
  padding: 8px 0;
}
</style>
